package com.zxt.web.controller;

import com.alibaba.fastjson.JSON;
import com.zxt.domain.User;
import com.zxt.domain.WeiXinResult;
import com.zxt.service.OrderService;
import com.zxt.service.impl.OrderServiceImpl;
import com.zxt.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * projectName:myXiaoMi
 * author:ZhangXiaoTeng
 * time:2021/12/8 16:02
 * description:
 */
@WebServlet("/paySuccess")
public class PaySuccessServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        //判断用户是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
           response.sendRedirect(request.getContextPath()+"/login.jsp");
           return;
        }
        //2.获取前端数据
        String result = request.getParameter("result");
        if (StringUtils.isEmpty(result)){
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return;
        }
        //3.处理结果
        WeiXinResult weiXinResult = JSON.parseObject(result, WeiXinResult.class);
        String oid = weiXinResult.getResult().getOut_trade_no();
        if (weiXinResult.getResult().getResult_code().equals("SUCCESS")){

        //支付状态成功 修改订单支付状态
        //类型0为页面重定向  1为点对点服务器通信  因为是localhost地址  无法使用1
        if (weiXinResult.getType()==0){
            OrderService orderService=new OrderServiceImpl();
            orderService.updateState(oid,2);    //1.未支付  2.已支付未发货  3.已发货  4.已完成
            request.setAttribute("msg",oid+"已支付成功,已通知商家发货");
            request.getRequestDispatcher("/message.jsp").forward(request,response);
        }else if (weiXinResult.getType()==1){
            System.out.println("点对点通讯");
        }
        }else {
            request.setAttribute("msg",oid+"支付失败");
            request.getRequestDispatcher("/message.jsp").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

